# encoding:utf8
import logging

from django.contrib import auth
from django.http import HttpResponseRedirect
from django.shortcuts import render

from user import service
from user.forms import LoginForm, RegisterForm
from user.models import UserModel

LOG = logging.getLogger(__name__)


def login(request):
    error_message = ""
    if request.method == "POST":
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            username = login_form.cleaned_data['username']
            password = login_form.cleaned_data['password']
            user = auth.authenticate(username=username, password=password)
            if user and user.is_active:
                auth.login(request, user)
                error_message = "用户登录成功"
                LOG.debug(error_message)
                return HttpResponseRedirect("/")
            else:
                error_message = "用户登录失败, 用户名或密码无效"
                LOG.debug(error_message)
        else:
            error_message = "输入不合法, 请重新输入"
            LOG.debug(error_message)
    else:
        LOG.debug("加载登录页面")
        login_form = LoginForm()
    return render(request, 'user/login.html', {"login_form": login_form, "error_message": error_message})


def register(request):
    error_message = ""
    if request.user.is_authenticated():
        LOG.debug("用户已经登录，直接跳转到主界面")
        return HttpResponseRedirect("/")
    if request.method == 'POST':
        register_form = RegisterForm(request.POST)
        if not register_form.is_valid():
            error_message = "用户输入不合法，注册失败"
            LOG.debug(error_message)
            return render(request, 'user/register.html',
                          {"register_form": register_form, 'error_message': error_message})
        elif register_form.cleaned_data["password"] != register_form.cleaned_data["retry_password"]:
            error_message = "两次输入的密码不一致"
            LOG.debug(error_message)
            return render(request, 'user/register.html',
                          {"register_form": register_form, 'error_message': error_message})
        else:
            LOG.debug("用户输入注册信息有效，检查是否有重名用户")
            username = register_form.cleaned_data["username"]
            password = register_form.cleaned_data["password"]
            filter_result = UserModel.objects.filter(user__username=username)
            if len(filter_result) > 0:
                error_message = "注册失败，用户名重复"
                LOG.debug(error_message)
                return render(request, 'user/register.html',
                              {"register_form": register_form, 'error_message': error_message})
            else:
                service.save_user(register_form)
                # 使用新的账号密码进行登录
                new_user = auth.authenticate(username=username, password=password)
                if new_user is not None:
                    auth.login(request, new_user)
                    LOG.debug("注册新用户并登录成功")
                    return HttpResponseRedirect("/")
                else:
                    error_message = "注册新用户登录失败 %s %s" % (username, password)
                    LOG.debug(error_message)
                    return render(request, 'user/register.html',
                                  {"register_form": register_form, 'error_message': error_message})
    else:
        LOG.debug("GET请求加载注册页面")
        register_form = RegisterForm()
        return render(request, 'user/register.html', {"register_form": register_form, 'error_message': error_message})
